local articlesController = {}
local vaild = require 'library.vaild'
local db = require 'models.db'
local user = require 'library.user'
local helper = require 'library.helpers'
local page = require 'library.pageobj'

function articlesController:index()
    local p = {}
    local page_params = {}
    page_params['page']=":page:"
    local get = self:getRequest():getParams()
   
    local article_db=db:new('article','art') 
    local pageobj = page:new(article_db:count(),12,tonumber(get['page']),helper:url('admin/articles/index',page_params));
    local res = article_db:order('id desc'):limit(pageobj:limit()):get_list()

    article_db:clear()

    p['page'] = pageobj;
    p['articles'] = res;

   return self:display(p)
end

function articlesController:create()
    local tagsdb=db:new('tags')
    local p = {
       article={}, 
       tids={}, 
       url=helper:url('admin/articles/store'),
       tags=tagsdb:get_list(), 
    }
    return self:display('admin.articles/edit.html',p)
end

function articlesController:store()
    local article_db=db:new('article','art')
    local post=self:getRequest():POST()

    local id=tonumber(post['id'])
    local article={}
    if id and id>0 then
        article=article_db:where('id=?',id):get_one()
        if helper:is_empty_table(article) then
            return helper:show_msg(1,'错误,没有找到记录',{url=helper:url('admin/articles/index')});
        end
    end
    self:save(article)
end
function articlesController:save(article)

    local post=self:getRequest():POST()
    local vaild_my=vaild:new(post);
    vaild_my:add('title','required|max_length(255)','title error');
    vaild_my:add('content','required','content error');


    local now=ngx.localtime()

    if vaild_my:run() then
        local article_db=db:new('article','art')
        if helper:is_empty_table(article) then
            article['created_at']=now
        end
        article['title']=post['title']
        article['content']=post['content']
        article['updated_at']=now
        article['title_index']=''
        article['content_index']=''

        local ret=article_db:replace(article)

        if ret then
            if ret['insert_id'] then
                article['id']=ret['insert_id']
            end
            self:save_tags(article)--insert id
            self:redirect(helper:url('admin/articles/index'))
        end
    end
    helper:show_msg(1,'保存失败',{url=helper:url('admin/articles/index')});
end

function articlesController:save_tags(article)
    local articles_tags=db:new('articles_tags')
    local post=self:getRequest():POST()
    local article_db=db:new('article','art')
    articles_tags:where('aid=?',article['id']):delete()
    local tags=post['tags[]']

    if type(tags)~='table' then
        tags={tags}
    end

    if #tags>0 then
        local now=ngx.localtime()
        for _,v in ipairs(tags) do
            v=tonumber(v)
            if v>0 then
                articles_tags:insert({tid=v,aid=article['id'],created_at=now,updated_at=now})
                article_db:query("UPDATE pre_tags  as t SET t.num=(SELECT COUNT(*) FROM pre_articles_tags as pt WHERE pt.tid=t.id) where t.id ="..v)
            end
        end
    end
end

function articlesController:edit()
    local p = {}
    local get = self:getRequest():getParams()
    local id=tonumber(get['id']) 
    local article_db=db:new('article') 
    local articles_tags=db:new('articles_tags') 
    local tagsdb=db:new('tags')

    p['article']=article_db:where("id=?",id):get_one()

    if p['article'] then
        local tags=articles_tags:select("tid"):where('aid=?',p['article']['id']):get_list()
        local tids={}
        for k,v in pairs(tags) do
            tids[#tids+1]=v['tid']
        end

        p['tids']=tids
        p['tags']=tagsdb:select("id,tag_name"):get_list()
        p['url']=helper:url('admin/articles/store')

        return self:display(p)
    else
        return helper:show_msg(1,'错误,没有找到记录',{url=helper:url('admin/articles/index')});
    end
end

function articlesController:destroy()
    local p = {}
    local post=self:getRequest():POST()

    if helper:is_natural_no_zero(post['id']) then
        local article=db:new('article') 
        local articles_tags=db:new('articles_tags') 
        local tagsdb=db:new('tags')
        local comments=db:new('comments')
        comments:where('aid=?',post['id']):delete()
        articles_tags:where('aid=?',post['id']):delete()        
        article:where("id=?",post['id']):delete()
        self:redirect(helper:url('admin/articles/index'))
    end
    return helper:show_msg(1,'错误,没有找到记录',{url=helper:url('admin/articles/index')});
end

function articlesController:comment_close()
    local post=self:getRequest():POST()
    local id=helper:intval(post['aid'])

    if id>0 then
        local article=db:new('article') 
        local ret=article:query('update '..article.table.." set close_comment=abs(close_comment-1) where id='"..id.."'")
        if not ret then
            return helper:show_msg(1,'修改错误',{url=helper:url('admin/articles/index')});
        else
            return helper:show_msg(0,'开启成功',{url=helper:url('admin/articles/index')});
        end
    end
    return helper:show_msg(1,'错误,没有找到记录',{url=helper:url('admin/articles/index')});
end

return articlesController
